package com.xy.xymall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xy.common.exception.NoStockException;
import com.xy.common.utils.R;
import com.xy.common.vo.MemberRespVo;
import com.xy.xymall.order.constant.OrderConstant;
import com.xy.xymall.order.dao.OrderItemDao;
import com.xy.xymall.order.entity.OrderItemEntity;
import com.xy.xymall.order.enume.OrderStatusEnum;
import com.xy.xymall.order.feign.CartFeignService;
import com.xy.xymall.order.feign.MemberFeignService;
import com.xy.xymall.order.feign.ProductFeignService;
import com.xy.xymall.order.feign.WareFeignService;
import com.xy.xymall.order.interceptor.LoginUserInterceptor;
import com.xy.xymall.order.service.OrderItemService;
import com.xy.xymall.order.to.OrderCreateTo;
import com.xy.xymall.order.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xy.common.utils.PageUtils;
import com.xy.common.utils.Query;

import com.xy.xymall.order.dao.OrderDao;
import com.xy.xymall.order.entity.OrderEntity;
import com.xy.xymall.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    /*
     * 存放订单数据的ThreadLocal
     */
    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal=new ThreadLocal<>();

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @author XY
     * @date 2020/11/25 12:57
     * @return com.xy.xymall.order.vo.OrderConfirmVo
     * 订单确认页需要返回的数据
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        //1、远程查询所有的收获地址列表
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //获取到当前请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        //异步远程调用时线程不一样，RequestContextHolder是根据ThreadLocal获取数据的，所以线程不一样数据也不一样
        //所以在远程调用时可能拿不到请求头信息，就会报错，在请求前需要把信息重新设置才能正常请求
        CompletableFuture<Void> getAddress = CompletableFuture.runAsync(() -> {
            //先设置好请求属性，解决feign异步调用没有请求头问题
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            orderConfirmVo.setAddress(address);
        }, executor);
        List<OrderItemVo> userCartItem1 = cartFeignService.getUserCartItem();
        //2、远程查询购物车所有选中的购物项
        CompletableFuture<Void> getCart = CompletableFuture.runAsync(() -> {
            //先设置好请求属性，解决feign异步调用没有请求头问题
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> userCartItem = cartFeignService.getUserCartItem();
            //feign在远程调用之前要构造请求，调用很多的拦截器，feign在远程调用的时候请求会没有请求头
            orderConfirmVo.setItems(userCartItem);
        }, executor).thenRunAsync(()->{
            //查询库存信息
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            R skusHasStock = wareFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data = skusHasStock.getData(new TypeReference<List<SkuStockVo>>() {
            });
            if(data!=null){
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                orderConfirmVo.setStocks(map);
            }
        },executor);

        //3、查询用户积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //4、其他数据自动计算

        //5、防重令牌，用于解决接口幂等性问题，这里是解决订单重复提交问题
        String token = UUID.randomUUID().toString().replace("-", "");
        orderConfirmVo.setOrderToken(token);
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30, TimeUnit.MINUTES);

        CompletableFuture.allOf(getAddress,getCart).get();


        return orderConfirmVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SubmitOrderRespVo submitOrder(OrderSubmitVo vo) {
        confirmVoThreadLocal.set(vo);
        SubmitOrderRespVo submitOrderRespVo = new SubmitOrderRespVo();
        submitOrderRespVo.setCode(0);
        //获取用户信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        //1、验证令牌，【令牌的对比和删除必须保证原子性】
        //使用lua脚本保证redis操作原子性,返回0-失败或者1-成功
        String script="if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
        String orderToken=vo.getOrderToken();
        //原子验证令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        if(result==0L){
            //令牌验证失败
            submitOrderRespVo.setCode(1);
            return submitOrderRespVo;
        }else{
            //令牌验证成功
            //去服务器创建订单，验令牌，验价格，锁库存
            //1、创建订单
            OrderCreateTo order = createOrder();
            //2、验价
            BigDecimal payAmount = order.getOrderEntity().getPayAmount();
            BigDecimal payPrice = vo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
                //金额对比成功
                //3、保存到数据库
                saveOrder(order);
                //4、锁库存，只要有异常，回滚订单数据
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
                wareSkuLockVo.setOrderSn(order.getOrderEntity().getOrderSn());
                List<OrderItemEntity> orderItemEntities = order.getOrderItemEntities();
                List<OrderItemVo> locks = orderItemEntities.stream().map(item -> {
                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setTitle(item.getSkuName());
                    orderItemVo.setCount(item.getSkuQuantity());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setLocks(locks);
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if(r.getCode()==0){
                    //库存锁定成功
                    submitOrderRespVo.setOrderEntity(order.getOrderEntity());
                    return submitOrderRespVo;
                }else{
                    //库存锁定失败
                    String msg=(String) r.get("msg");
                    throw new NoStockException();
                }
            }else{
                submitOrderRespVo.setCode(2);
                return submitOrderRespVo;
            }

        }
//        String redisToken=stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId());
//        if(orderToken!=null&&orderToken.equals(redisToken)){
//
//        }else{
//
//        }
        //下单成功来到支付选择页
        //下单失败回到订单确认页重新确认订单信息
    }

    /**
     * @param order
     * @author XY
     * @date 2021/1/19 10:24
     * @Description 保存订单数据
     */
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrderEntity();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItemEntities = order.getOrderItemEntities();
        orderItemService.saveBatch(orderItemEntities);
    }

    /**
     * @Author XY
     * @Date 2021-01-16 9:34
     * @Param []
     * @Return com.xy.xymall.order.to.OrderCreateTo
     * 创建订单数据
     */
    private OrderCreateTo createOrder(){
        OrderCreateTo orderCreateTo=new OrderCreateTo();
        //1、生成订单号
        String orderSn= IdWorker.getTimeId();
        //创建订单号
        OrderEntity orderEntity = buildOrder(orderSn);
        orderCreateTo.setOrderEntity(orderEntity);
        //2、订单项
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderSn);
        orderCreateTo.setOrderItemEntities(orderItemEntities);
        //3、计算价格相关
        computePrice(orderEntity,orderItemEntities);
        return orderCreateTo;
    }

    /**
     * @param orderEntity
     * @param orderItemEntities
     * @author XY
     * @date 2021/1/18 16:13
     * @Description 计算价格相关
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total=new BigDecimal("0.0");
        BigDecimal integration=new BigDecimal("0.0");
        BigDecimal promotion=new BigDecimal("0.0");
        BigDecimal coupon=new BigDecimal("0.0");
        Integer gift=0;
        Integer growth=0;
        //订单的总额，叠加每一个订单项的金额
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            BigDecimal realAmount = orderItemEntity.getRealAmount();
            BigDecimal integrationAmount = orderItemEntity.getIntegrationAmount();
            BigDecimal promotionAmount = orderItemEntity.getPromotionAmount();
            BigDecimal couponAmount = orderItemEntity.getCouponAmount();
            Integer giftIntegration = orderItemEntity.getGiftIntegration();
            Integer giftGrowth = orderItemEntity.getGiftGrowth();
            gift+=giftIntegration;
            growth+=giftGrowth;
            total= total.add(realAmount);
            integration= integration.add(integrationAmount);
            promotion= promotion.add(promotionAmount);
            coupon= coupon.add(couponAmount);

        }
        //1、订单价格相关
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setCouponAmount(coupon);
        //2、积分信息
        orderEntity.setGrowth(growth);
        orderEntity.setIntegration(gift);
        orderEntity.setDeleteStatus(0);

    }

    /**
     * @param orderSn
     * @author XY
     * @date 2021/1/18 16:13
     * @Description 创建订单基本信息
     */
    private OrderEntity buildOrder(String orderSn) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity=new OrderEntity();
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberId(memberRespVo.getId());
        //获取收货地址信息
        OrderSubmitVo orderSubmitVo = confirmVoThreadLocal.get();
        R fare = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = fare.getData(new TypeReference<FareVo>() {
        });
        //运费信息
        orderEntity.setFreightAmount(fareVo.getFare());
        //收货人信息
        orderEntity.setReceiverCity(fareVo.getMemberAddressVo().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getMemberAddressVo().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getMemberAddressVo().getName());
        //订单状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }

    /**
     * @Author XY
     * @Date 2021-01-16 9:35
     * @Param []
     * @Return com.xy.xymall.order.entity.OrderItemEntity
     * 构建所有订单项数据
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> userCartItems = cartFeignService.getUserCartItem();
        List<OrderItemEntity> collect=null;
        if(userCartItems!=null&&!userCartItems.isEmpty()){
            collect = userCartItems.stream().map(item -> {
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return collect;
    }

    /**
     * @Author XY
     * @Date 2021-01-16 9:36
     * @Param [item]
     * @Return com.xy.xymall.order.entity.OrderItemEntity
     * 构建单条订单项数据
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1、spu信息
        Long skuId = item.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(data.getId());
        orderItemEntity.setSpuName(data.getSpuName());
        orderItemEntity.setSpuBrand(data.getBrandId().toString());
        orderItemEntity.setCategoryId(data.getCatalogId());
        //2、sku信息
        orderItemEntity.setSkuId(item.getSkuId());
        orderItemEntity.setSkuName(item.getTitle());
        orderItemEntity.setSkuPic(item.getImage());
        orderItemEntity.setSkuPrice(item.getPrice());
        List<String> skuAttr = item.getSkuAttr();
        String skuAttrs = StringUtils.collectionToDelimitedString(skuAttr, ";");
        orderItemEntity.setSkuAttrsVals(skuAttrs);
        orderItemEntity.setSkuQuantity(item.getCount());
        //3、优惠信息【不做】
        //4、积分信息
        orderItemEntity.setGiftGrowth(item.getPrice().intValue());
        orderItemEntity.setGiftIntegration(item.getPrice().intValue());
        //5、订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal(0));
        orderItemEntity.setIntegrationAmount(new BigDecimal(0));
        orderItemEntity.setCouponAmount(new BigDecimal(0));
        //当前订单项的实际金额
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity()));
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount()).subtract(orderItemEntity.getIntegrationAmount())
                .subtract(orderItemEntity.getPromotionAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

}